const app = getApp();
const https = require('../../utils/https');
const nowHour = (new Date()).getHours() > 19 ? 2 : 1
const nextDay = new Date((Date.now() + 60 * 60 * 24 * 1000 * nowHour))
const nextMonthDay = new Date((Date.now() + 60 * 60 * 24 * 1000 * 30))
const formatStartDay = `${nextDay.getFullYear()}-${ ('0' + (nextDay.getMonth()+1)).substr(-2)}-${('0' + (nextDay.getDate())).substr(-2)}`
const formatEndDay = `${nextMonthDay.getFullYear()}-${ ('0' + (nextMonthDay.getMonth()+1)).substr(-2)}-${('0' + (nextMonthDay.getDate())).substr(-2)}`
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 上传户型图
    certificate: '../../images/upload4.png',
    certificates: '',
    // 验房类型
    inspection: [], // 房屋类型 精装 or 毛坯
    type: ['1', '2'],
    inspector_id: null, // 直接扫验房师二维码进来时有值
    inspection_id: 2, // 选中的房屋类型 默认精装房
    price: 0.00,
    coupon_count: 0,
    type_name: '请选择验房类型',
    coupon_text: '暂无可使用优惠券',
    //预约时间初始化
    date: '',
    datePlacehoder: '选择预约日期',
    time: '',
    timeArray: [],
    TimePlacehoder: '请选择时间段',
    start_date: formatStartDay,
    end_date: formatEndDay,
    // 小区位置
    baseAreaData: [],
    areaRange:[],
    region: [0,0,0],
    name: '',
    area: 0,
    multiSelector: [],
    regionActive: '请选择',
    city: '',
    showTimer: null,
    book_order_deposit: null, // 定金金额
    loupanRange:[],
    loupanActive: '',
    loupan_id: null, // 楼盘id
    maskShow: false,
    btnLodding:false,
    btnDisabled:false,
  },
  //验房类型选择
  bindtypeChange: function (e) {
    var id = e.currentTarget.dataset.id,
        index = this.data.inspection.findIndex(i => i.id === parseInt(id));
    const {area, loupanRange, loupan_id} =  this.data
    const inspection = this.data.inspection[index]
    this.setData({
      type_name: inspection.name,
      inspection_id: inspection.id,
      max_area: inspection.area,
    })
    console.log(loupan_id)
    // 没有我的楼盘，取房屋类型上的价格
    if(loupan_id === -1) {
      this.setData({
        salse_price: inspection.salse_price,
        old_price: inspection.salse_price,
        send_price: inspection.salse_price
      })
    } else if(loupan_id){
      console.log('loupanRange', loupanRange)
      const loupan = loupanRange.find(l => l.id === parseInt(loupan_id))
      // 判断是用毛坯价格 还是 精装价格
      const price = inspection.id === 2 ? loupan.price : loupan.maopi_price;
      this.setData({
        salse_price: price,
        old_price: price,
        send_price: price
      })
    }
    if(area > 0){
     this.checkPrice();
    }
  },
  // 日期选择
  bindDateChange: function (e) {
    this.setData({
      date: e.detail.value
    })
    const {time_id, loupan_id, date} = this.data;
    this.checkLoupanAndTime(loupan_id, date, time_id);
  },
  // 时间段选择
  bindTimeChange(e) {
    const time = this.data.timeArray[e.detail.value]
    this.setData({
      time: time.name,
      time_id: time.id
    })
    const {time_id, loupan_id, date} = this.data;
    this.checkLoupanAndTime(loupan_id, date, time_id)
  },
  //地址选择
  bindRegionChange: function (e) {
    console.log(e)
    this.setData({
      region: e.detail.value,
      regionActive: this.data.areaRange[0][e.detail.value[0]] + this.data.areaRange[1][e.detail.value[1]] + this.data.areaRange[2][e.detail.value[2]],
      city: this.data.areaRange[1][e.detail.value[1]],
      loupanRange:[],
      loupanActive: ''
    })
    var that = this;
    https.post('getLoupan', {zone: that.data.areaRange[2][e.detail.value[2]] }, false).then(res => {
      that.setData({
        loupanRange: [...res, {id: -1, name: "没有我的楼盘", price: "3" }]
      })
    })
  },
  // 地址选择器 列改变
  bindColumnChange: function (e) {
    console.log(e.detail, 'value: ', e.detail.value, 'column: ', e.detail.column)
    const index = e.detail.value;
    const data = {
      region: this.data.region,
      areaRange: this.data.areaRange,
      baseAreaData: this.data.baseAreaData
    };
    data.region[e.detail.column] = index;
    switch (e.detail.column) {
      case 0:
        data.areaRange[1] = data.baseAreaData[index].city.map(c => c.name);
        data.areaRange[2] = data.baseAreaData[index].city[0].zone.map(c => c.name);
        data.region[1] = 0;
        data.region[2] = 0;
        break;
      case 1:
        data.areaRange[2] = data.baseAreaData[data.region[0]].city[index].zone.map(c => c.name);
        data.region[2] = 0;
        break;
    }
    console.log(data);
    this.setData(data);
  },
  // 楼盘选择
  bindLoupanChange: function (e) {
    const {area, loupanRange, inspection_id} = this.data;
    const loupan = loupanRange[e.detail.value]
    // 判断是用毛坯价格 还是 精装价格
    const price = inspection_id === 2 ? loupan.price : loupan.maopi_price;
    this.setData({
      loupanActive: loupan.name,
      loupan_id: loupan.id,
      salse_price: price,
      old_price: price,
      send_price: price
    })
    // 没有我的楼盘，取房屋类型上的价格
    if(loupan.id === -1) {
      const inspection = this.data.inspection.find(i => i.id === inspection_id) // 选中的房屋类型
      if(inspection) {
        this.setData({
          salse_price: inspection.salse_price,
          old_price: inspection.salse_price,
          send_price: inspection.salse_price
        })
      }
    }
    if(area > 0){
      this.checkPrice();
    }
  },
  // 楼盘初始化 -- 从首页带数据
  loupanInit(province, city, zone, loupan, loupan_id) {
    const { inspection_id} = this.data
    this.setData({
      regionActive: province + city + zone,
      city: city,
      loupanRange:[],
      loupanActive: ''
    })
    https.post('getLoupan', {zone}, false).then(res => {
      this.setData({
        loupanRange: [...res, {id: -1, name: "没有我的楼盘", price: "3", maopi_price: "2.6" }]
      })
      const item = res.find(a => a.id === parseInt(loupan_id))
      console.log(item)
      if(item) {
        // 判断是用毛坯价格 还是 精装价格
        const price = inspection_id === 2 ? item.price : item.maopi_price;
        console.log(price)
        this.setData({
          loupanActive: loupan,
          loupan_id: loupan_id,
          salse_price: price,
          old_price: price,
          send_price: price
        })
      }
    })
  },
  // 上传户型图012
  certificateImg: function (e) {
    var that = this
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        that.setData({
          certificate: tempFilePaths,
          certificates: tempFilePaths,
          certificateFirst: true
        });
      }
    })
  },
  getAreaData(){
    https.post('getRegArea', null, false, '正在查询').then(res => {
      this.setData({
        baseAreaData: res,
        areaRange: [res.map(p => p.name), res[0].city.map(c => c.name), res[0].city[0].zone.map( z => z.name)]
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
   
    if(options && options.scene && options.scene.indexOf("inspector") == 0) {
      this.setData({
        inspector_id: options.scene.replace("inspector", "")
      })
    }
    if(options.province && options.city && options.zone && options.loupan && options.loupan_id) {
      this.loupanInit(options.province, options.city, options.zone, options.loupan, options.loupan_id)
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.getMsgList();
    this.getPeriods();
    this.getAreaData();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
   
    var that = this;

    var t = setTimeout(() => {
      var login_status = wx.getStorageSync('login_status');
      var user_tel = wx.getStorageSync('tel');
   
      if (!login_status || login_status <= 0) {
        wx.showLoading({
          title: '请先进行登陆',
        })
        setTimeout(() => {
          wx.hideLoading({
            success: (res) => {
              wx.navigateTo({
                url: '/pages/grant/grant',
              })
            },
          })
        }, 1500);
      } else if(!user_tel) {
       
        wx.navigateTo({
         url: '/pages/signin/signin',
        })
      } else {
        that.getInspection();
        that.getUserInfo();
        that.getSystemConfig();
        that.getCouponInfo(); //获取优惠券信息
      }
    }, 200)
    this.setData({
      showTimer: t
    })
  },
  /**
   * @xk 获取用户信息
   * @param {} res
   */
  getUserInfo: function (res) {
    var that = this,
      user_id = wx.getStorageSync('user_id');
    https.post('getUserInfo', {
      user_id: user_id
    }, true).then(res => {
      that.setData({
        user_info: res
      })
    })
  },
  // 获取定金金额
  getSystemConfig: function (res) {
    var that = this,
        user_id = wx.getStorageSync('user_id');
    https.post('getSystemConfig', {
      user_id: user_id
    }, true).then(res => {
      that.setData({
        book_order_deposit: res.book_order_deposit
      })
    })
  },
  /**
   * @xk 选择优惠券
   */
  chooseCoupon: function () {
    app.globalData.order_type = 'gbook';
    wx.navigateTo({
      url: '/pages/my_coupon/coupon',
    })
  },
  checkPrice: function(){
    let {area, max_area, price, salse_price} = this.data;
    console.log('area:',area, ',max_area:', max_area, ',price:',price, ',salse_price:',salse_price)
    if(!salse_price || !max_area) return
    if(area > max_area){
      price = area * salse_price;
    }else{
      price = max_area * salse_price;
    }
    console.log(price,area)
    this.setData({
      price: price,
      area: area,
      send_price: price,
    })
    this.getPrice();
  },
  chanageArea: function(obj){
    var area = obj.detail.value;
    this.setData({
      area: area,
    })
    this.checkPrice();
  },
  /**
   * @xk 获取验房类型
   * @param {*} res
   */
  getInspection: function (res) {
    var that = this,
      user_id = wx.getStorageSync('user_id'),
      coupon_text = this.data.coupon_text;
    https.post('getInspection', {user_id: user_id}, false, '正在查询').then(res => {
      if (res.coupon_count > 0) {
        coupon_text = res.coupon_count + '张可用';
      }else{
        coupon_text = '首页领取优惠券';
      }
      that.setData({
        inspection: res.list,
        coupon_text: coupon_text,
        coupon_count: res.coupon_count
      })
      that.bindtypeChange({currentTarget: {dataset: {id: 2}}})
    })
  },
  /**
   * @xk 获取优惠券信息 选中的
   * @param {*} res
   */
  getCouponInfo: function (res) {
    var that = this,
      user_coupon_id = app.globalData.user_coupon_id;
    if (user_coupon_id > 0) {
      https.post('getUserCouponInfo', {
        user_coupon_id: user_coupon_id
      }, true).then(res => {

        if (res) {
          that.setData({
            coupon_info: res
          })
          that.getPrice();
        } else {
          that.setData({
            coupon_text: '暂无满足条件的优惠券'
          })
        }
      })
    }
  },

  /**
   * @xk 计算价格显示问题
   */
  getPrice: function () {
    var that = this,
      price = this.data.price,
      send_price = this.data.send_price,
      coupon_info = this.data.coupon_info;
    // 开始判断
    if (coupon_info) {
      if (send_price < coupon_info['need_money']) {
        wx.showToast({
          title: '优惠券不满足使用条件',
          icon: 'none',
          duration: 1500
        })
        this.setData({
          coupon_text: '优惠券不满足使用条件',
          coupon_info: '',
        })
        app.globalData.user_coupon_id = 0;
      } else {
        that.setData({
          coupon_text: '使用优惠券抵扣' + coupon_info['money'],
          price: send_price-coupon_info['money']
        })
      }
    } else {
      that.setData({
        coupon_text: '请选择需要使用优惠券',
        coupon_info: '',
      })
      app.globalData.user_coupon_id = 0;
    }
  },
  getPeriods: function () {
    const that = this;
    https.post('getPeroid', {

    }, true,).then(res => {
      that.setData({
        timeArray: res
      })
    })
  },
  // 检查时间段是否可用
  checkLoupanAndTime: function (loupan_id, booking_date, peroid_id) {
  
    if(!loupan_id || loupan_id === -1 || !booking_date || !peroid_id) return
    https.post('loupanCheck', {
      loupan_id, booking_date, peroid_id
    }, true,).then(res => {
      console.log(res)
    })
  },
  /**
   * @xk 提交预约验房订单
   * @param {} res
   */
  Submit: function (obj) {
    var that = this,
      inspection_id = this.data.inspection_id,
      price = this.data.send_price,
      user_coupon_id = app.globalData.user_coupon_id,
      book_time = `${obj.detail.value['date']} ${obj.detail.value['time']}`,
      tel = obj.detail.value['tel'],
      name = obj.detail.value['name'],
      position = this.data.regionActive,
      address = obj.detail.value['address'],
      house_area_1 = obj.detail.value['house_area_1'],
      house_area_2 = obj.detail.value['house_area_2'],
      house_area_3 = obj.detail.value['house_area_3'],
      area = obj.detail.value['area'],
        loupan = obj.detail.value['loupanActive']? obj.detail.value['loupanActive']:this.data.loupanActive  ,
        loupan_id = this.data.loupan_id,
      newList = this.data.certificates;
    if (inspection_id <= 0) {
      wx.showToast({
        title: '请选择验房类型',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    if (book_time.trim() == '' || book_time == "选择预约时间") {
      wx.showToast({
        title: '请选择预约时间',
        icon: 'none',
        duration: 1500
      })
      return false;
    }

    if (name == '') {
      wx.showToast({
        title: '请填写预约人姓名',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    if (tel == '') {
      wx.showToast({
        title: '请填写预约人电话',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    if (position == '' || position == '小区位置') {
      wx.showToast({
        title: '请选择小区位置',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    if (!loupan_id) {
      wx.showToast({
        title: '请选择楼盘',
        icon: 'none',
        duration: 1500
      })
      return false;
    }


    if (address == '') {
      wx.showToast({
        title: '请填写详细地址',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    if (house_area_1 == '' || house_area_2 == '' || house_area_3 == '') {
      wx.showToast({
        title: '请填写楼门牌号等',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    if (area == '' && area <= 0) {
      wx.showToast({
        title: '请填写建筑面积',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    that.setData({
      inspection_id: inspection_id,
      price: price,
      book_time: book_time,
      user_coupon_id: user_coupon_id,
      tel: tel,
      name: name,
      position: position,
      address: address,
      house_area: house_area_1 + '-' + house_area_2 + '-' + house_area_3,
      area: area,
      loupan,
      loupan_id,
      btnLodding:true,
      btnDisabled:true
    })

    if (newList.length > 0) {
      that.uploadPic({
        path: newList
      });
    } else {

      that.formsubimt();
    }

  },

  formsubimt: function (obj) {
    var that = this,
      inspection_id = this.data.inspection_id,
      price = this.data.price,
      book_time = this.data.book_time,
      user_coupon_id = this.data.user_coupon_id,
      name = this.data.name,
      tel = this.data.tel,
      position = this.data.position,
      address = this.data.address,
      house_area = this.data.house_area,
      area = this.data.area,
      user_id = wx.getStorageSync('user_id'),
      city = this.data.city,
      pics = this.data.pics,
        loupan = this.data.loupan,
        loupan_id = this.data.loupan_id,
        inspector_id = this.data.inspector_id,
        promote_user_id = app.globalData.promote_user_id || ''; // 推荐人
      
        //return false
    https.post('saveBookOrder', {
      inspection_id: inspection_id,
      price: price,
      book_time: book_time,
      user_coupon_id: user_coupon_id,
      tel: tel,
      city: city,
      name: name,
      position: position,
      address: address,
      house_area: house_area,
      area: area,
      user_id: user_id,
      pics: pics,
      loupan_id: loupan_id === -1 ? null : loupan_id,
      loupan,
      promote_user_id: promote_user_id, // 推荐人
      inspector_id, // 验房师直扫
    }, false,'正在提交预约').then(res => {
      app.globalData.user_coupon_id = 0;
      app.globalData.order_sn = res.order_sn;
      if(res.code == 205){
        //执行微信支付
        wx.requestPayment({
          timeStamp: res.pay_info.timeStamp,
          nonceStr: res.pay_info.nonceStr,
          package: res.pay_info.package,
          signType: res.pay_info.signType,
          paySign: res.pay_info.paySign,
          success (res) {
            if(res.errMsg == 'requestPayment:ok'){
              that.setData({
                btnLodding:false
              })
              wx.showToast({
                title: '支付成功',
                icon: 'none',
                duration: 1500
              })
              // that.submsg()
              that.maskShow()

            }else{
              wx.showToast({
                title: '支付取消',
                icon: 'none',
                duration: 2000
              })
              wx.redirectTo({
                url: '/pages/booking_order/booking_order',
              })
            }

          },
          fail (res) {
            wx.showToast({
              title: '支付取消 ',
              icon: 'none',
              duration: 1500
            })
            wx.redirectTo({
              url: '/pages/booking_order/booking_order',
            })
          }
        })
      }else{
        wx.redirectTo({
          url: '/pages/appointment_result/appointment_result',
        })
      }
    })
  },
  getMsgList(){
    const that = this;
    wx.request({
      url: 'https://info.amagich.com/wx/submsg-list',
      data: {

      },
      method: "post",
      success: function (res) {
        const {data} = res.data;
        that.setData({
          tmplIds: data
        })

      }
    })
  },
  submsg() {
    const that = this;
    const {tmplIds} = that.data;
    if(!tmplIds) {
      return
    };
    wx.requestSubscribeMessage({
      tmplIds: tmplIds.map(msg => msg.template_id),
      success (res2) {
       
      },
      fail (res2) {
        
      },
    })
  },
  uploadPic: function (data) {
    var pics = this.data.pics ? this.data.pics : '';
    var that = this;
    var i = data.i ? data.i : 0; //当前上传的哪张图片
    var success = data.success ? data.success : 0; //上传成功的个数
    var fail = data.fail ? data.fail : 0; //上传失败的个数
    var photo_urls = this.data.photo_urls ? this.data.photo_urls : [];
    wx.uploadFile({
      url: https.url + 'upload',
      filePath: data.path[i],
      name: 'file', //这里根据自己的实际情况改
      formData: {
        id: data.id
      }, //这里是上传图片时一起上传的数据
      success: (resp) => {
        if (resp.data != '') {
          success++; //图片上传成功，图片上传成功的变量+1
          wx.showLoading({
            title: '上传第' + success + '张完成',
          })
          if (pics != '') {
            pics = pics + ',' + resp.data
          } else {
            pics = resp.data
          }
        } else {
          fail++
        }
        that.setData({
          pics: pics,
          imgs: [],
        })
        //这里可能有BUG，失败也会执行这里,所以这里应该是后台返回过来的状态码为成功时，这里的success才+1
      },
      fail: (res) => {
        fail++; //图片上传失败，图片上传失败的变量+1
      },
      complete: () => {
        i++; //这个图片执行完上传后，开始上传下一张
        if (i == data.path.length) { //当图片传完时，停止调用
          wx.hideLoading();
          wx.showToast({
            title: '上传完成',
            icon: 'success',
            duration: 1000
          });
          setTimeout(function () {
            that.formsubimt();
          }, 1000);

        } else { //若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadPic(data);
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
   

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
   

    if(this.data.showTimer) {
      clearTimeout(this.data.showTimer)
      this.setData({
        showTimer: null
      })
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.onShow();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var timestamp = Date.parse(new Date()),
    app_name = wx.getStorageSync('app_name'),
    app_logo = wx.getStorageSync('app_logo'),
    user_id = wx.getStorageSync('user_id'),
    url = '/pages/home/home',
    timestr = timestamp / 1000;
    url += '?timestr=' + timestr;
    if (user_id > 0) {
      url += '&l_id=' + user_id;
    }
    return {
      title: app_name,
      path: url,
      imageUrl: app_logo
    }
  },
  maskHide:function () {
    this.setData({
      maskShow: false
    })
    wx.redirectTo({
      url: '/pages/appointment_result/appointment_result',
    })
  },
  maskShow:function () {
    this.setData({
      maskShow: true
    })
  }
})
